package book.pojo;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * sql动态参数类
 */
public class DynamicParameter implements Serializable {
    @Setter
    private String baseSql;
    //字符串缓冲器，用于存储sql语句
    private StringBuilder builder = new StringBuilder();
    //参数名列表对象
    private ArrayList<String> paramNameList = new ArrayList<>();
    //参数值列表对象
    @Getter
    private ArrayList<Object> paramValueList = new ArrayList<>();
    //运算符列表对象
    private ArrayList<String> flagList = new ArrayList<>();
    //构造函数，初始化sql基本语句
    public DynamicParameter(String baseSql){
        this.baseSql = baseSql;
        builder.append(baseSql);
    }

    /**
     * 拼接sql参数，返回完整的sql语句
     * 给分页查询使用
     * @return
     */
    public String generateSqlForPage(){
        builder.append(" where 1=1 ");
        //循环拼接sql语句
        for(int i=0;i<paramNameList.size();i++){
            builder.append("and "+paramNameList.get(i)+" "+this.flagList.get(i)+" ? ");
        }
        //添加分页查询
        builder.append(" limit ?,?");
        return builder.toString();
    }

    /**
     * 给查询总记录数使用
     * @return
     */
    public String generateSqlForTotalCount(){
        //清除基本sql
        builder.setLength(0);
        //重新设置
        builder.append(baseSql);
        builder.append(" where 1=1 ");
        //循环拼接sql语句
        for(int i=0;i<paramNameList.size();i++){
            builder.append("and "+paramNameList.get(i)+" "+this.flagList.get(i)+" ? ");
        }
        return builder.toString();
    }
    /**
     * 动态添加参数
     * @param paramName     参数名
     * @param paramValue    参数值
     * @param flag          sql运算符
     */
    public void addParam(String paramName,Object paramValue,String flag){
        this.paramNameList.add(paramName);
        if("like".equalsIgnoreCase(flag)){
            //模糊查询
            this.paramValueList.add("%"+paramValue+"%");
        }else{
            this.paramValueList.add(paramValue);
        }
        this.flagList.add(flag);
    }
}
